package com.fayou.auth.securityauthservice.controller;


import cn.hutool.core.util.IdUtil;
import com.fayou.auth.securityauthservice.domain.LoginResponse;
import com.fayou.cloud.entites.LoginRequest;
import com.fayou.cloud.entites.ResponseCodeEnum;
import com.fayou.cloud.entites.ResponseResult;
import com.fayou.cloud.util.JWTUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    /**
     * Apollo 或 Nacos
     */
    @Value("${secretKey:123456}")
    private String secretKey;


    @PostMapping("/login")
    public ResponseResult login(@RequestParam @Validated LoginRequest request, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(ResponseCodeEnum.PARAMETER_ILLEGAL.getCode(), ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
        }

        String username = request.getUsername();
        String password = request.getPassword();

        String userId = "1001";
        if ("hello".equals(username) && "world".equals(password)) {
            //  生成Token
            String token = JWTUtil.generateToken(userId, secretKey);

            //  生成刷新Token
            String refreshToken = IdUtil.randomUUID();

            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setToken(token);
            loginResponse.setRefreshToken(refreshToken);
            loginResponse.setUsername(userId);

            return ResponseResult.success(loginResponse);
        }

        return ResponseResult.error(ResponseCodeEnum.LOGIN_ERROR.getCode(), ResponseCodeEnum.LOGIN_ERROR.getMessage());
    }
}
